# Usage: MAP_CHECK_MODULE(RESULT_VAR [dependencies ...] )
# check if all required modules exist and stores missing module names in RESULT_VAR.
MACRO(MAP_CHECK_MODULE RESULT_VAR)
  SET(${RESULT_VAR} "")
  SET(DEPENDS "")
  SET(DEPENDS_BEFORE "not initialized")
  SET(PACKAGE_DEPENDS "")
  
  
  # check for each parameter if it is a package (3rd party)
  FOREACH(package ${ARGN})
    SET(is_package)
    FOREACH(dir ${MODULES_PACKAGE_DEPENDS_DIRS})
      IF(EXISTS "${dir}/MAP_${package}_Config.cmake") 
        LIST(APPEND PACKAGE_DEPENDS ${package})
        SET(is_package 1)
        BREAK()
      ENDIF()
    ENDFOREACH()
    IF(NOT is_package)
      LIST(APPEND DEPENDS ${package}) 
    ENDIF()
  ENDFOREACH(package)

  # create a list of all lowercase module names
  FILE(GLOB _ALL_MODULES RELATIVE ${MAP_MODULES_CONF_DIR} ${MAP_MODULES_CONF_DIR}/*Config.cmake)
  SET(_ALL_MODULES_LOWERCASE "")
  FOREACH(_module ${_ALL_MODULES})
    STRING(TOLOWER ${_module} _lowermodule)
    LIST(APPEND _ALL_MODULES_LOWERCASE ${_lowermodule})
  ENDFOREACH(_module ${_ALL_MODULES})

  WHILE(NOT "${DEPENDS}" STREQUAL "${DEPENDS_BEFORE}")
    SET(DEPENDS_BEFORE ${DEPENDS})
    FOREACH(dependency ${DEPENDS})
      
      SET(_dependency_file_name ${dependency}Config.cmake)
      LIST(FIND _ALL_MODULES ${_dependency_file_name} _index)
      IF(NOT _index EQUAL -1)
        INCLUDE(${MAP_MODULES_CONF_DIR}/${dependency}Config.cmake)
        IF(${dependency}_IS_ENABLED)
          LIST(APPEND DEPENDS ${${dependency}_DEPENDS})
          LIST(APPEND PACKAGE_DEPENDS ${${dependency}_PACKAGE_DEPENDS})
        ELSE(${dependency}_IS_ENABLED)
          LIST(APPEND ${RESULT_VAR} ${dependency})
          LIST(REMOVE_DUPLICATES ${RESULT_VAR})
        ENDIF(${dependency}_IS_ENABLED)
      ELSE(NOT _index EQUAL -1)
        STRING(TOLOWER ${_dependency_file_name} _lowercase_dependency_file_name)
        LIST(FIND _ALL_MODULES_LOWERCASE ${_lowercase_dependency_file_name} _index_lower)
        IF(NOT _index_lower EQUAL -1)
          LIST(GET _ALL_MODULES ${_index_lower} _real_module_name)
          STRING(REPLACE "Config.cmake" "" _real_module_name ${_real_module_name})
          MESSAGE("Warning: case mismatch for module name ${dependency}, did you mean ${_real_module_name} ?")
        ENDIF(NOT _index_lower EQUAL -1)
        LIST(APPEND ${RESULT_VAR} ${dependency})
        LIST(REMOVE_DUPLICATES ${RESULT_VAR})
      ENDIF(NOT _index EQUAL -1)

    ENDFOREACH(dependency) 
    LIST(REMOVE_DUPLICATES DEPENDS)
    LIST(REMOVE_DUPLICATES PACKAGE_DEPENDS)
    LIST(SORT DEPENDS)
    LIST(SORT PACKAGE_DEPENDS)
  ENDWHILE()
  
  FOREACH(_package PACKAGE_DEPENDS)
    IF((DEFINED MAP_USE_${_package}) AND NOT (${MAP_USE_${_package}}))
      LIST(APPEND ${RESULT_VAR} ${_package})
    ENDIF()  
  ENDFOREACH()

ENDMACRO(MAP_CHECK_MODULE)
